<script setup>
import {getCurrentInstance, reactive, ref} from "vue";
import {cloneDeep} from "lodash";
import {addDictType, getDictType, updateDictType} from "@/api/system/dict_type";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success']);
const modalRef = ref();
const formRef = ref();
const formData = ref({
  dictId: undefined,
  dictName: '',
  dictCode: '',
  remark:''
})
const rules = reactive({
  dictName: [{required: true, message: '请输入字典名称', trigger: 'blur'}],
  dictCode: [{required: true, message: '请输入字典编码', trigger: 'blur'}]
})
const formType = ref('create')


const open = async (id, type = 'create') => {
  formType.value = type;
  resetForm();
  if (type === 'update') {
    const {data} = await getDictType(id);
    formData.value = {
      ...data
    }
  }
  modalRef.value.handleOpen()
}

const handleSubmit = async () => {
  const result = await formRef.value.validate();
  if(result){
    return false;
  }
  let data = cloneDeep(formData.value);
  if (data.dictId === undefined) {
    await addDictType(data);
    proxy.$modal.okNotify('新增成功');
  } else {
    await updateDictType(data);
    proxy.$modal.okNotify('修改成功');
  }
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    dictId: undefined,
    dictName: '',
    dictCode: '',
    remark:''
  }
}

defineExpose({open})
</script>

<template>
  <dialog-form ref="modalRef" :modalTitle="`${formType === 'create' ? '新建' : '编辑'}字典`" modalWidth="500px"
               @submit="handleSubmit">
    <a-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <a-form-item label="字典名称" field="dictName">
        <a-input v-model="formData.dictName" placeholder="请输入字典名称"/>
      </a-form-item>
      <a-form-item label="字典编码" field="dictCode">
        <a-input v-model="formData.dictCode" placeholder="请输入字典编码"/>
      </a-form-item>
      <a-form-item label="备注" field="remark">
        <a-textarea v-model="formData.remark" placeholder="请输入内容"/>
      </a-form-item>
    </a-form>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
